<?php
class Agitum_Model_Geo extends Agitum_Model_Tree
{
	protected $_t_class = 'Agitum_Model_DbTable_Geo';

	public static function search($term, $level)
	{
		$db = Zend_Registry::get('Zend_Db');
		
		$sub = $db->select()
			->from( array('b' => 'geo'), array('title'))
			->where( 'b.trail @> a.trail' )
			->order('b.trail desc');
		
		$select = $db->select();
		$select->from(array('a'=>'geo'), array( 'id', 'title' => new Zend_Db_Expr('array('.$sub.')') ))
			->where( new Zend_Db_Expr('a.title like '. $db->quote($term.'%')) )
			;
		
		if ($level) {
			$select->where( 'a.level = ? ', $level );
		}

		$data = $select->query()->fetchAll();
		
		$parser = new DB_Pgsql_Type_Array(new DB_Pgsql_Type_String());
		for ($i = 0; $i < count($data); $i++ ) {
			$data[$i]['title'] = implode(', ', $parser->input($data[$i]['title']) );
		}
		return $data;
	}
	
	public static function fetchMapLevel($level = 1) 
	{
		$db = Zend_Registry::get('Zend_Db');
		$select = $db->select()
			->from('geo')
			->where('level = ? ', $level)
			->order('title asc');
		$data = $select->query()->fetchAll();
		$map = array();
		foreach ( $data as $i => $row ) {
			$map[ $row['id'] ] = $row;
		}
		unset($data);
		return $map;
	}
	
	public static function fetchMapId($ids) 
	{
	    $db = Zend_Registry::get('Zend_Db');
	    $select = $db->select();
		$select->from('geo')
			->where( new Zend_Db_Expr('id IN ('. implode(',', $ids) .')') )
			->order('title asc')
			;
		
		$rows = $select->query()->fetchAll();
		$data = array();
		foreach ($rows as $i => $row) {
		    $data[$row['id']] = $row;
		}
		unset($rows);
		return $data;
	}
}